"""
# 交互特征
"""
import pandas as pd
from sklearn.linear_model import LinearRegression
from sklearn.model_selection import train_test_split
import sklearn.preprocessing as preproc

# 假设df是一个Pandas数据框，其中包含了UCI在线新闻流行度数据集
df = pd.read_csv('../数据集/OnlineNewsPopularity.csv', delimiter=',')
# 选择与内容有关的特征作为模型的单一特征，忽略那些衍生特征
features = [' n_tokens_title',
            ' n_tokens_content',
            ' n_unique_tokens',
            ' n_non_stop_words',
            ' n_non_stop_unique_tokens',
            ' num_hrefs',
            ' num_self_hrefs',
            ' num_imgs',
            ' num_videos',
            ' average_token_length',
            ' num_keywords',
            ' data_channel_is_lifestyle',
            ' data_channel_is_entertainment',
            ' data_channel_is_bus',
            ' data_channel_is_socmed',
            ' data_channel_is_tech',
            ' data_channel_is_world']
X = df[features]
Y = df[[' shares']]
# 创建交互特征对，跳过固定偏移项
X2 = preproc.PolynomialFeatures(include_bias=False).fit_transform(X)
# 为两个特征集创建训练集和测试集
X1_train, X1_test, X2_train, X2_test, y_train, y_test = train_test_split(X, X2, Y, test_size=0.3, random_state=123)
# 在两个特征集上训练模型并比较R方分数
model = LinearRegression().fit(X1_train, y_train)
score = model.score(X1_test, y_test)
print("R-squared score with singleton features: {:.5}".format(score))
model = LinearRegression().fit(X2_train, y_train)
score = model.score(X2_test, y_test)
print("R-squared score with pairwise features: {:.5}".format(score))
